import React from 'react';
// 引入路由的组件
import { BrowserRouter, useRoutes, useLocation, useNavigate } from 'react-router-dom';

// 获取所有的页面路由
import routes from '~react-pages';

// 引入路由规则
import rules from '@/routers/rules';

import type business from './types/business';
import 'antd-mobile/es/global';

const App = () =>
{
    const Routers = () =>
    {
        const { pathname } = useLocation();
        const navigate = useNavigate();

        React.navigate = navigate;

        useEffect(() => {
            const check = async () =>
            {
                // 白名单路由直接返回
                if (rules.includes(pathname)) {
                    return;
                }

                // 获取登录信息
                const business = React.Cookies.load('business') || {};

                if (!business || Object.keys(business).length === 0) {
                    React.fail('请先登录', () => {
                        navigate('/business/login');
                    });
                    return;
                }

                try {
                    const result = await React.Http.post('/business/check', {
                        id: business.id || 0,
                        mobile: business.mobile || 0
                    });
            
                    if (result.code === 1) {
                        React.Cookies.save('business', result.data, { path: '/' });
                        React.business = result.data as business;
                    } else {
                        React.fail(result.msg, () => {
                            React.Cookies.remove('business', { path: '/' });
                            React.business = {} as business;
                            navigate('/business/login');
                        });
                    }
                } catch (error) {
                    React.Cookies.remove('business', { path: '/' });
                    React.business = {} as business;
                    navigate('/business/login');
                }
            }

            check();
        }, [pathname, navigate]);

        return (
            <React.Suspense>
                {useRoutes(routes)}
            </React.Suspense>
        )
    }

    return (
        <BrowserRouter>
            <Routers />
        </BrowserRouter>
    )
}

export default App;